import asyncio
import time
import datetime
import socket
import json

ipaddr = socket.gethostbyname(socket.getfqdn(socket.gethostname()))


async def task1():
    while 1:
        message = json.dumps({
            "event": "heart",
            "data": {
                "logtime": datetime.datetime.now().strftime("%H:%M:%S"),
                "host": ipaddr,
                "status": "online"
            }
        })
        reader, writer = await asyncio.open_connection("127.0.0.1", 8888)

        print(f"Send: {message}")
        writer.write(message.encode('utf-8'))
        await writer.drain()

        data = await reader.read(1024)
        print(f"Received: {data.decode('utf-8')}")

        print("Close the connection")
        writer.close()
        time.sleep(10)


async def task2():
    await asyncio.sleep(2)
    print("Task 2 finished")


async def main():
    tasks = [task1(), task2()]
    await asyncio.gather(*tasks)


asyncio.run(main())